package com.zcf.controller;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zcf.utils.JavaLarLng;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.internal.util.StringUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageHelper;
import com.zcf.common.json.Body;
import com.zcf.common.result.PageResult;
import com.zcf.common.result.ResultVo;
import com.zcf.mapper.ClasssMapper;
import com.zcf.mapper.CollectMapper;
import com.zcf.mapper.DiningMapper;
import com.zcf.mapper.ProductMapper;
import com.zcf.mapper.UserMapper;
import com.zcf.mappers.Demo;
import com.zcf.pojo.Classs;
import com.zcf.pojo.Dining;
import com.zcf.pojo.Log;
import com.zcf.pojo.Messages;
import com.zcf.pojo.Orderinfo;
import com.zcf.pojo.Product;
import com.zcf.pojo.Riding;
import com.zcf.pojo.Shopp;
import com.zcf.pojo.Shopping;
import com.zcf.pojo.Subordinate;
import com.zcf.pojo.User;
import com.zcf.service.DiningService;
import com.zcf.utils.AppPush;
import com.zcf.utils.DateUtil;
import com.zcf.utils.Hutool;
import com.zcf.utils.zhifubao.Query;
import com.zcf.vo.in.PageVo;
import com.zcf.vo.in.PersonageInviteController;
import com.zcf.vo.out.AMapUtils;
import com.zcf.vo.out.LngLat;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhouzhuang
 * @since 2018-11-28
 */
@Controller
@RequestMapping("/dining")
@CrossOrigin
@ResponseBody
public class DiningController {

    @Autowired
    CollectMapper collectMapper;

    @Autowired
    DiningMapper diningMapper;

    @Autowired
    DiningService diningService;

    @Autowired
    ProductMapper productMapper;

    @Autowired
    ClasssMapper classsMapper;
    @Autowired
    UserMapper usermapper;

    /**
     * 查詢所有
     *
     * @return
     */
    @PostMapping("addDiningAll")
    public Body addDiningAll() {

        return diningService.addDiningAll();
    }

    /**
     * 查询单个商家信息
     */
    @PostMapping("queryDiningOne")
    public Body queryDiningOne(String id) {
        Dining dining = new Dining();
        dining = dining.selectById(id);
        if (dining == null) {
            return Body.BODY_451;
        }
        Subordinate subordinate = new Subordinate();
        EntityWrapper<Subordinate> ew = new EntityWrapper<>();
        ew.eq("din_id", id);
        subordinate = subordinate.selectOne(ew);
        if (subordinate == null) {
            return Body.BODY_451;
        }
        dining.setProportion(subordinate.getProportion() + "");
        if (dining != null) {
            return Body.newInstance(dining);
        }
        return Body.BODY_500;
    }

    /**
     * 进入菜单页面
     */
    @PostMapping("getCaiDan")
    public Body getCaiDan(String user_id, String id, String class_id) {
        Dining dining = new Dining();
        int count = collectMapper.getCount(user_id, id);
        dining.setId(id);
        dining = dining.selectById();
        if (dining == null) {
            return Body.newInstance(-1, "店铺不存在");
        }
        EntityWrapper<Product> ew = new EntityWrapper<>();
        ew.eq("dining_id", id);
        if (class_id != null) {
            ew.eq("class_id", class_id);
        }
        ew.eq("type", 1);
        List<Product> list = productMapper.selectList(ew);

        EntityWrapper<Classs> ews = new EntityWrapper<>();
        ews.eq("din_id", id);
        List<Classs> lists = classsMapper.selectList(ews);
        if (lists.size() > 0) {
            dining.setClassses(lists);
        }
        dining.setTypes(count);// 是否收藏
        ShoppController shoppController = new ShoppController();
        Shopping shopp = new Shopping();
        shopp.setDinId(id);
        shopp.setUserId(user_id);
        Body shoppings = shoppController.addShoppinges(shopp);

        Shopp shopp2 = new Shopp();
        EntityWrapper<Shopp> ewp = new EntityWrapper<>();
        ew.eq("user_id", user_id);
        ew.eq("din_id", id);
        List<Shopp> l = shopp2.selectList(ewp);
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < l.size(); j++) {
                if (list.get(i).getId().equals(l.get(j).getProductId())) {
                    if (!StringUtils.isEmpty(l.get(j).getNumber())) {
                        list.get(i).setFoodnumzzc(Integer.parseInt(l.get(j).getNumber()));
                    }
                }
            }
        }
        if (list.size() > 0) {
            dining.setProduct(list);
        }
        dining.setShoppings(shoppings);
        return Body.newInstance(dining);
    }

    /**
     * 修改营业状态
     */
    @PostMapping("updateStatus")
    public Body updateStatus(String id, Integer status) {
        Dining dining = new Dining();
        dining.setId(id);
        dining.setStatus(status);
        Boolean flag = dining.updateById();
        if (flag) {
            return Body.BODY_200;
        }
        return Body.BODY_500;
    }

    /**
     * 搜索
     */
    @PostMapping("queryLiShi")
    public Body queryLiShi(String diningName, String productName, String userId) {
        Messages messages = new Messages();
        EntityWrapper<Messages> ew = new EntityWrapper<>();
        ew.eq("user_id", userId);
        if (diningName != null) {
            ew.eq("concent", diningName);
        }
        if (productName != null) {
            ew.eq("concent", productName);
        }
        List<Messages> list = messages.selectList(ew);
        if (list.size() == 0) {
            messages.setMessageId(Hutool.getId());
            messages.setAddtime(Hutool.parseDateToString());
            messages.setUserId(userId);
            if (diningName != null) {
                messages.setConcent(diningName);
            }
            if (productName != null) {
                messages.setConcent(productName);
            }
            messages.insert();
        }
        return diningService.queryCountSou(diningName, productName);
    }

    /**
     * 查询店铺
     */
    @PostMapping("query")
    public Body query(PageVo pv, Integer sum, Double lat1, Double lng1) {
        ResultVo rv = diningService.queryXianJian(pv, sum, lat1, lng1);
        if (rv == null) {
            return Body.newInstance("查询失败");
        }
        return Body.newInstance(rv);
    }

    /**
     * 查询店铺
     */
    @PostMapping("queryXianJie")
    public Body queryXianJie(PageVo pv, String sum, String lat1, String lng1, String address, String largeId) {
//		List<Dining> list = diningMapper.queryCount(sum);
        EntityWrapper<Dining> ew = new EntityWrapper<>();
        if (address != "" && address != null) {
            ew.like("address", address);
        }
        if (largeId != "" && largeId != null) {
            ew.eq("large_id", largeId);
        }
        if (sum != "" && sum != null) {
            int num = Integer.parseInt(sum);
            if (num == 1) {
                ew.orderBy("grade", false);
            } else if (num == 2) {
                ew.orderBy("grade", true);
            } else if (num == 3) {
                ew.orderBy("sums", false);
            } else if (num == 4) {
                ew.orderBy("sums", true);
            }
        }
        List<Dining> list = diningMapper.selectList(ew);
        if (lat1 == null && lng1 == null) {
            if (list.size() > 0) {
                return Body.newInstance(list);
            }
            return Body.newInstance("查无数据");
        }
        List<Dining> lists = new ArrayList<>();
        double distance = 0.0;

        for (Dining dining : list) {
            JavaLarLng javaLarLng = new JavaLarLng();
            double lat2 = Double.parseDouble(dining.getLatitude());
            double lng2 = Double.parseDouble(dining.getLongitude());
//			distance = MapUtils.GetDistance(lat1, lng1, lat2, lng2);

            double lat11 = Double.parseDouble(lat1);
            double lng11 = Double.parseDouble(lng1);

            LngLat start = new LngLat(lng11, lat11);
            LngLat end = new LngLat(lng2, lat2);
            distance = AMapUtils.calculateLineDistance(start, end);
            dining.setDistance(distance);
            if (distance > 0) {
                if (Integer.parseInt(sum) == 5) {
                    lists = list.stream().sorted(Comparator.comparing(Dining::getDistance).reversed())
                            .collect(Collectors.toList());// 根据距离逆序
                } else {
                    lists.add(dining);
                }
            }
        }
        if (pv.getPage() != null && pv.getPageSize() != null) {
            PageHelper.startPage(pv.getPage(), pv.getPageSize());
        }
        PageResult pr = PageResult.result(lists);
        ResultVo rv = new ResultVo();
        rv.setList(pr.getRows());
        rv.setTotal(pr.getTotal());

        if (rv != null) {
            return Body.newInstance(rv);
        }
        return Body.newInstance("查无数据");
    }

    /**
     * 查询推荐
     */
    @PostMapping("getTuijian")
    public Body getTuijian(String address) {
        List<Dining> lists = diningMapper.getTuijian(address);
        if (lists.size() > 0) {
            return Body.newInstance(lists);
        } else {
            List<Dining> lists2 = diningMapper.getTuijian(null);
            return Body.newInstance(lists2);
        }
        //return Body.newInstance("查无数据");
    }

    /**
     * 代理-查询商家
     */
    @PostMapping("getDiningDaili")
    public Body getDiningDaili(String userId, String dinName, String address) {
        System.err.println(userId);
        User user = new User();
        user = user.selectById(userId);
        if (user != null) {
            EntityWrapper<Dining> ew = new EntityWrapper<>();
            if (dinName != null && dinName != "") {
                ew.like("dining_name", dinName);
            }

            String filename = user.getAddress();
            String levelCode = filename.substring(filename.indexOf("省") + 1).trim();// 逗号后面
            String levelCodes = levelCode.substring(0, levelCode.indexOf("区") + 1).trim();// 逗号前面
            levelCodes = levelCodes.substring(0, levelCodes.length() - 1);
            if (user.getAddress() != null) {
                ew.like("address", levelCodes);
            }
            Dining dining = new Dining();
            List<Dining> list = dining.selectList(ew);

            List<Dining> lists = new ArrayList<>();
            for (Dining dining2 : list) {
                if (dining2.getNotice().equals("0")) {
                    dining2.setWlx("未推荐");
                } else {
                    dining2.setWlx("推荐");
                }
                lists.add(dining2);
            }
            if (lists.size() < 0) {
                return Body.newInstance("查无数据");
            }
            return Body.newInstance(lists);
        }
        return Body.BODY_451;
    }

    /**
     * 查询商家
     */
    @PostMapping("getDining")
    public Body getDining(String dinName, String address, String notice) {
        EntityWrapper<Dining> ew = new EntityWrapper<>();
        if (dinName != null) {
            ew.like("dining_name", dinName);
        }
        if (address != null) {
            ew.like("address", address);
        }
        if (notice != null && notice != "") {
            ew.like("notice", notice);
        }
        Dining dining = new Dining();
        List<Dining> list = dining.selectList(ew);

        List<Dining> lists = new ArrayList<>();
        for (Dining dining2 : list) {
            if (dining2.getNotice().equals("0")) {
                dining2.setWlx("未推荐");
            } else {
                dining2.setWlx("推荐");
            }
            Subordinate subordinate = new Subordinate();
            EntityWrapper<Subordinate> ews = new EntityWrapper<>();
            ews.eq("din_id", dining2.getId());
            subordinate = subordinate.selectOne(ews);
            if (subordinate != null) {
                dining2.setProportion(subordinate.getProportion() + "");
            } else {
                dining2.setProportion("2");
            }
            lists.add(dining2);
        }
        if (lists.size() < 0) {
            return Body.newInstance("查无数据");
        }
        return Body.newInstance(lists);
    }

    /**
     * 删除商家
     */
    @PostMapping("delete")
    public Body delete(String id) {
        String[] appid = id.split(",");
        Boolean flag = false;
        Dining din = new Dining();
        for (int i = 0; i < appid.length; i++) {
            din.setId(appid[i]);
            flag = din.deleteById();
        }
        if (flag == true) {
            return Body.newInstance("删除成功");
        }
        return Body.newInstance("删除失败");
    }

    /**
     * 推荐商家
     */
    @PostMapping("getTuijianShang")
    public Body getTuijianShang(String id) {
        String[] appid = id.split(",");
        Boolean flag = false;
        Dining din = new Dining();
        for (int i = 0; i < appid.length; i++) {
            din.setId(appid[i]);
            din.setNotice("1");
            din.setAddtime(Hutool.parseDateToString());
            flag = din.updateById();
        }
        if (flag == true) {
            return Body.newInstance("推荐成功");
        }
        return Body.newInstance("推荐失败");
    }

    /**
     * 取消推荐商家
     */
    @PostMapping("setTuijianShang")
    public Body setTuijianShang(String id) {
        String[] appid = id.split(",");
        Boolean flag = false;
        Dining din = new Dining();
        for (int i = 0; i < appid.length; i++) {
            din.setId(appid[i]);
            din.setNotice("0");
            flag = din.updateById();
        }
        if (flag == true) {
            return Body.newInstance("取消成功");
        }
        return Body.newInstance("取消失败");
    }

    /**
     * 发布或修改简介
     */
    @PostMapping("insertNotice")
    public Body insertNotice(String dinId, String diningIntro, String diningTag) {
        Dining dining = new Dining();
        dining.setId(dinId);
        dining = dining.selectById();
        if (dining != null) {
            dining.setDiningIntro(diningIntro);
            dining.setDiningTag(diningTag);
            Boolean flag = dining.updateById();
            if (flag) {
                return Body.newInstance(dining);
            }
            return Body.newInstance("修改失败");
        }
        return Body.newInstance("商家不存在");
    }

    /**
     * 商家接单
     *
     * @throws Exception
     */
    @PostMapping("updateOrdersDining")
    public Body updateOrdersDining(String orderInfoId) throws Exception {
        Orderinfo orderinfo = new Orderinfo();
        orderinfo.setOrderInfoId(orderInfoId);
        orderinfo = orderinfo.selectById();
        if (orderinfo != null) {
            String time = Hutool.parseDateToString();
            String sum = DateUtil.dateDiff(orderinfo.getAddtime(), time, "yyyy-MM-dd HH:mm:ss", "m");
            String num = DateUtil.dateDiff(orderinfo.getAddtime(), time, "yyyy-MM-dd HH:mm:ss", "h");
//			if (Integer.parseInt(sum) > 5 || Integer.parseInt(num) > 1) {
//				// 订单已超时
//				orderinfo.setStatus(5);
//				orderinfo.setDinStatus(3);
//				Boolean flag = orderinfo.updateById();
//				if (flag) {
//					AliAndWXRefund.wxRefund(0.01, orderinfo.getOrderInfoId());
//					Query.refundMoney(orderinfo.getOrderInfoId(), 0.01);
//					return Body.newInstance("订单已超时");
//				}
//				return Body.BODY_500;
//			} else {
            Dining dining = new Dining();

            dining.setId(orderinfo.getDinId());
            dining = dining.selectById();
            if (dining.getLargeId().equals("7")) {
//线下核销
                orderinfo.setStatus(2);
                orderinfo.setDinStatus(2);
                Boolean flag = orderinfo.updateById();
                User user = new User();
                user.setId(dining.getUserId());
                user = user.selectById();
                user.setMoney(user.getMoney() + orderinfo.getTotalMoney());
                user.updateById();
                return Body.newInstance(orderinfo);
            } else {
                orderinfo.setStatus(1);
                orderinfo.setDinStatus(1);
                Boolean flag = orderinfo.updateById();
                if (flag) {
                    Riding riding = new Riding();
                    List<Riding> list = riding.selectAll();
                    // 逆地理
                    PersonageInviteController percentageController = new PersonageInviteController();
                    for (Riding riding2 : list) {
                        if (riding2.getLatitude() != null && riding2.getLongitude() != "" && riding2.getLatitude() != ""
                                && riding2.getLongitude() != null) {
                            String address = percentageController.Geocoding(riding2.getLatitude(), riding2.getLongitude());
                            riding2.setAddress(address);
                            riding2.updateById();
                        }
                    }
                    Dining dining2 = new Dining();
                    dining2.setId(orderinfo.getDinId());
                    dining2 = dining2.selectById();
                    String filename = dining2.getAddress();
                    String levelCode = filename.substring(filename.indexOf("省") + 1).trim();// 逗号后面
                    String levelCodes = levelCode.substring(0, levelCode.indexOf("市") + 1).trim();// 逗号前面
                    System.err.println(levelCodes);
                    Riding riding2 = new Riding();
                    EntityWrapper<Riding> ews = new EntityWrapper<>();
                    if (levelCodes != null && levelCodes != "") {
                        ews.like("address", levelCodes);
                    }
                    List<Riding> lists = riding2.selectList(ews);
                    for (Riding riding3 : lists) {
                        if (riding3.getUserId() == null) {
                            continue;
                        }
                        User user = new User();
                        user = usermapper.selectById(riding3.getUserId());
                        if (user != null) {
                            if (!user.getCid().equals("") && user.getCid() != null) {
                                // 个推
                                AppPush.pushinfo(user.getCid());
                            }
                        }
                    }
                    User user = new User();
                    user.setId(orderinfo.getUserId());
                    user = user.selectById();
                    if (user != null) {
                        if (!user.getCid().equals("") && user.getCid() != null) {
                            // 个推
                            AppPush.pushinforiding(user.getCid());
                        }
                    }
                    return Body.newInstance(orderinfo);
                }
                return Body.BODY_500;
//			}
            }
        }
        return Body.BODY_500;
    }

    /**
     * 商家拒绝接单
     *
     * @throws Exception
     */
    @PostMapping("updateJuJueOrderInfo")
    public Body updateJuJueOrderInfo(HttpServletRequest request, HttpServletResponse response, String orderInfoId)
            throws Exception {
        Orderinfo orderinfo = new Orderinfo();
        orderinfo.setOrderInfoId(orderInfoId);
        orderinfo = orderinfo.selectById();
        if (orderinfo != null) {
            if (orderinfo.getPayment().equals("1")) {
                WXpayController wXpayController = new WXpayController();
                Double money = 0.0;
//				if (orderinfo.getCouponMoney() != null) {
                money = orderinfo.getTotalMoney();// - Double.parseDouble(orderinfo.getCouponMoney());
//				}
                if (AliAndWXRefund.wxRefund(money, orderinfo.getOrderNumber()) > 0) {
                    orderinfo.setStatus(5);
                    orderinfo.setDinStatus(3);
                    Boolean flag = orderinfo.updateById();
                    if (flag) {
                        return Body.newInstance("退款成功");
                    }
                }
                return Body.newInstance("退款失败");
            } else {
                Double money = 0.0;
//				if (orderinfo.getCouponMoney() != null) {
                money = orderinfo.getTotalMoney();//- Double.parseDouble(orderinfo.getCouponMoney());
//				}
                Double prices = money;
                Boolean flag = Query.refundMoney(orderinfo.getOrderNumber(), prices);
                if (flag) {
                    orderinfo.setStatus(5);
                    orderinfo.setDinStatus(3);
                    orderinfo.updateById();

                    User user = new User();
                    user.setId(orderinfo.getUserId());
                    user.selectById();
                    if (user != null) {
                        Log log = new Log();
                        log.setLogId(Hutool.getId());
                        log.setAddtime(Hutool.parseDateToString());
                        log.setMoneys(orderinfo.getTotalMoney() + "");
                        log.setLogDesc("ZFBTK");
                        log.setLogType(1);
                        log.setLogName(user.getName() + ":支付宝退款" + orderinfo.getTotalMoney() + "元");
                        log.insert();
                    }
                    return Body.newInstance("退款成功");
                }
                return Body.newInstance("退款失败");
            }
        }
        return Body.BODY_500;

    }

    /**
     * 修改商家logo
     */
    @PostMapping("updateLogo")
    public Body updateLogo(String logo, String dinId) {
        Dining dining = new Dining();
        if (dinId != null) {
            dining.setId(dinId);
            dining = dining.selectById();
        }
        if (dining == null || dinId == null) {
            return Body.newInstance("商家不存在");
        }
        dining.setLogo(logo);
        Boolean flag = dining.updateById();
        if (flag) {
            return Body.newInstance("修改成功");
        }
        return Body.BODY_500;
    }

    /**
     * 修改横条图片
     */
    @PostMapping("updateImages")
    public Body updateImages(Dining dining1, String userid) {
        Dining dining = new Dining();
        if (userid != null && !userid.equals("")) {
            EntityWrapper<Dining> ew = new EntityWrapper<>();
            ew.eq("user_id", userid);
            dining = dining.selectOne(ew);
        }
        if (dining == null) {
            return Body.newInstance(-1, "商家不存在");
        }
        if (dining1.getImage() != null) {
            dining.setImage(dining1.getLogo());
            dining.setLogo(dining1.getLogo());
        }
        if (dining1.getLogo() != null) {
            dining.setLogo(dining1.getLogo());
            dining.setImage(dining1.getLogo());
        }
        if (dining1.getDiningName() != null) {
            dining.setDiningName(dining1.getDiningName());
        }
        if (dining1.getPhone() != null) {
            dining.setPhone(dining1.getPhone());
        }
        if (dining1.getAddress() != null) {
            dining.setAddress(dining1.getAddress());
            // 根据地址获取经纬度
            Demo demo = new Demo();
            Object s = demo.gaodeditu(dining1.getAddress());
            String appid1 = s.toString();
            String lon[] = appid1.split(",");
            String latitude = "";
            String longitude = "";
            for (int i1 = 0; i1 < lon.length; i1++) {
                String string1 = lon[i1];
                if (i1 == 0) {
                    longitude = string1;
                } else {
                    latitude = string1;
                }
            }
            dining.setLongitude(longitude);
            dining.setLatitude(latitude);
        }
        if (dining1.getDiningIntro() != null) {
            dining.setDiningIntro(dining1.getDiningIntro());
        }
        if (dining1.getBox() != null) {
            dining.setBox(dining1.getBox());
        }
        Boolean flag = dining.updateById();
        if (flag) {
            return Body.newInstance(1, "修改成功");
        }
        return Body.newInstance(-2, "修改失败");
    }

    /**
     * 店铺详情
     */
    @PostMapping("addXiangQIng")
    public Body addXiangQIng(String dinId) {
        Dining dining = new Dining();
        dining.setId(dinId);
        dining = dining.selectById();
        if (dining != null) {
            return Body.newInstance(dining);
        }
        return Body.BODY_500;
    }
}
